# coding: utf-8

import datetime
import time
import json
import pymongo

from fraMail.framail import FraMail
from fralog.FraLog import *
from RedisOper import RedisOper
from settings import *
from dbproxy.dbproxy import DBProxy
from globalsettings import CUR_MODE

if CUR_MODE == 'dev':
    from globalsettings_dev import *
else:
    from globalsettings_prod import *

log = getFileLog()


class MonitorProcess(object):
    def __init__(self):
        super(MonitorProcess, self).__init__()
        self._redis = RedisOper.RedisOper
        client = pymongo.MongoClient(host=MONGO_HOST, port=MONGO_PORT)
        self._db = client['survey_database']
        self.fra_mail = FraMail()

    def monitor_type_0(self, code, channel, emails):
        #
        # 先统计对应的code, channel下记录的总条数
        #
        rows = self._db[data_collection].find({'code': code, 'response.channel': channel})
        count = rows.count()
        log.debug('记录的总条数: %d' % count)
        #
        # 统计人数
        rows_distinct = rows.distinct('response.wxid')
        uv = len(rows_distinct)
        log.debug('参与人数: %d' % uv)

        msg = '<h2>Fra 问卷参与度监控</h2><br>'
        msg += '<hr><h3>问卷code：%s<br>公司编码: %s</h3>' % (code, channel)
        msg += '<hr><h3>用户答卷总次数<font style="color:#ff0000; font-size:25px; position: relative; margin-left: 20px">%d</font></h3>' % count
        msg += '<hr><h3>参与问卷用户数<font style="color:#ff0000; font-size:25px; position: relative; margin-left: 20px">%d</font></h3><hr>' % uv
        self.fra_mail.login()
        emails = emails.split(',')
        for email in emails:
            self.fra_mail.send(email, msg, '问卷监控')
        self.fra_mail.logout()

    def _monitor(self):
        """
        遍历监控队列，发送监控邮件
        :return: 
        """
        task_count = self._redis.llen(task_key)
        log.info('当前总监控任务数: %d' % task_count)
        for i in range(task_count):
            data = self._redis.lindex(task_key, i)
            if data is None:
                log.error('无法获取监控任务')
                continue
            try:
                data = json.loads(data.decode())
                code = data['code']
                channel = data['channel']
                type = data['type']
                emails = data['emails']
                log.debug('code: %s , channel: %s  emails: %s' % (code, channel, emails))
                func_name = 'monitor_type_%d' % type
                func = MonitorProcess.__dict__[func_name]
                func(self, code, channel, emails)
            except Exception as e:
                log.error(e)

    def main_monitor(self):
        """
        监控主进程, 每天上午10点，下午4点各发一次邮件
        """
        log.info('开始监控')
        while True:
            current_time = time.localtime(time.time())
            hour = current_time.tm_hour
            min = current_time.tm_min
            # if True:
            if hour in email_hour and min == 5:
                log.info('开始发送邮件')
                self._monitor()
                log.info('邮件发送完毕')
                time.sleep(200)
            else:
                time.sleep(10)


if __name__ == '__main__':
    mp = MonitorProcess()
    mp.main_monitor()
    # mp.monitor_type_0(code='canfu-hr', channel='canfu',emails=None)
